package com.ruoyi.repairCar.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.repairCar.domain.dto.RescueRequestDTO;
import com.ruoyi.repairCar.service.RescueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.repairCar.domain.RescueTask;
import com.ruoyi.repairCar.service.IRescueTaskService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 救援任务Controller
 * 
 * @author djt
 * @date 2025-03-21
 */
@RestController
@RequestMapping("/rescueTask")
public class RescueTaskController extends BaseController
{
    @Autowired
    private IRescueTaskService rescueTaskService;

    @Autowired
    private RescueService rescueService;

    /**
     * 查询救援任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(RescueTask rescueTask)
    {
        startPage();
        List<RescueTask> list = rescueTaskService.selectRescueTaskList(rescueTask);
        return getDataTable(list);
    }

    /**
     * 导出救援任务列表
     */

    @Log(title = "救援任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RescueTask rescueTask)
    {
        List<RescueTask> list = rescueTaskService.selectRescueTaskList(rescueTask);
        ExcelUtil<RescueTask> util = new ExcelUtil<RescueTask>(RescueTask.class);
        util.exportExcel(response, list, "救援任务数据");
    }

    /**
     * 获取救援任务详细信息和会员信息
     */

//    @GetMapping(value = "/{memberId}")
//    public AjaxResult getInfo(@PathVariable("memberId") Long memberId) {
//        List<RescueTask> list = rescueTaskService.selectRescueTaskList(new RescueTask());
//        for (RescueTask rescueTask : list) {
//         //监控订单状态     此处还有bug，rescueTask.getOrderStatus()为null！！！
//            if (rescueTask.getOrderStatus().equals("1")) {
//                return AjaxResult.error("该订单正在进行中");
//            }
//            if (rescueTask.getOrderStatus().equals("2")) {
//                return AjaxResult.error("该订单已完成");
//            }
//        }
//        return success(rescueTaskService.selectRescueTaskByRescueId(memberId));
//    }

    /**
     * 新增救援任务
     */

//    @Log(title = "救援任务", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody RescueTask rescueTask)
//    {
//        return toAjax(rescueTaskService.insertRescueTask(rescueTask));
//    }

    /**
     * 修改救援任务
     */

    @Log(title = "救援任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RescueTask rescueTask)
    {
        return toAjax(rescueTaskService.updateRescueTask(rescueTask));
    }

    /**
     * 删除救援任务
     */

    @Log(title = "救援任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{rescueIds}")
    public AjaxResult remove(@PathVariable Long[] rescueIds)
    {
        return toAjax(rescueTaskService.deleteRescueTaskByRescueIds(rescueIds));
    }


    @Log(title = "救援任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RescueTask rescueTask) {
        // 基础校验
        if (rescueTask.getMemberId() == null) {
            return AjaxResult.error("用户ID不能为空");
        }

        try {
            // 转换DTO对象
            RescueRequestDTO requestDTO = convertToRequestDTO(rescueTask);

            // 执行MQ处理流程
            rescueService.processRescueRequest(requestDTO);

            // 保存到数据库（状态设为处理中）
            rescueTask.setOrderStatus("1");
            return toAjax(rescueTaskService.insertRescueTask(rescueTask));
        } catch (Exception e) {
            return AjaxResult.error("救援请求发送失败：" + e.getMessage());
        }
    }

    private RescueRequestDTO convertToRequestDTO(RescueTask task) {
        RescueRequestDTO dto = new RescueRequestDTO();
        // 基础字段映射
        dto.setRescueType(Math.toIntExact(task.getRescueType()));
        dto.setMemberId(task.getMemberId().intValue());
        dto.setVehicleNumber(task.getVehicleNumber());
        dto.setSituationExplanation(task.getSituationExplanation());

        // MQ配置（可从配置中心读取）
        RescueRequestDTO.MQConfig mqConfig = new RescueRequestDTO.MQConfig();
        mqConfig.setInitialRange(1);
        mqConfig.setMaxRetryRange(3);
        mqConfig.setRetryInterval(10000);
        dto.setMqConfig(mqConfig);

        // 地理信息（从前端获取或根据地址解析）
        RescueRequestDTO.GeoLocation geo = new RescueRequestDTO.GeoLocation();
        geo.setLatitude(Double.valueOf(task.getExt2()));
        geo.setLongitude(Double.valueOf(task.getExt3()));
        geo.setCoordinateSystem("GCJ-02");
        dto.setGeolocation(geo);

        return dto;
    }

}
